package com.springboot.springbootapi.web.api;

import com.alibaba.fastjson.JSON;
import com.springboot.springbootapi.model.User;
import com.springboot.springbootapi.repository.UserRepository;
import com.springboot.springbootapi.service.UserService;
import com.springboot.springbootapi.service.dto.UserDTO;
import com.springboot.springbootapi.web.vm.UserVM;
import org.dom4j.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

//接口请求入口
@RestController
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;
    //获取用户列表接口
    @GetMapping("/users")
    public String getList(){
        List<User> users = userRepository.findAll();
        List<UserDTO> userDTO= users.stream().map(x -> new UserDTO(x)).sorted(Comparator.comparingInt(p -> p.getAge())).collect(Collectors.toList());

        return JSON.toJSONString(userDTO);
    }
    //注册用户的接口

    @PostMapping("/users")
    public String addUser(@RequestBody UserVM  userVM){

        if(!userVM.getPasswordTow().equals(userVM.getPassword())){
            return "再次输入密码与密码不相同！";
        }


       User user = userService.addUser(userVM);
       if(user != null){
           return "注册成功！";
       }
       else {
           return "注册失败！";
       }
    }

    //删除用户
    @DeleteMapping("/users/{id}")
    public String deleteUser(@PathVariable Integer id) {
        userRepository.deleteById(id);
        return "删除成功！";
    }

    //编辑用户信息
    @PutMapping("/users/{id}")
    public String updateUser(@PathVariable Integer id,@RequestBody UserVM userVM){
    userService.updateUser(id,userVM);
    return "编辑成功！";
    }


}

